<?php

namespace app\codekey\admin;

use app\system\admin\Admin;
use app\codekey\model\UserGroupCodekey as UserGroupCodekeyModel;
use app\user\model\User as UserModel;
use app\user\model\UserGroup;

class Index extends Admin
{
    protected $oneModel = 'UserGroupCodekey'; //模型名称[通用添加、修改专用]
    protected $oneTable = ''; //表名称[通用添加、修改专用]
    protected $oneAddScene = ''; //添加数据验证场景名
    protected $oneEditScene = ''; //更新数据验证场景名

    public function initialize()
    {
        parent::initialize();
        $this->UserGroupCodekeyModel = new UserGroupCodekeyModel();
        $this->UserModel = new UserModel();
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            $map    = $data = [];
            $data   = input();
            if (isset($data['keyword']) && !empty($data['keyword'])) {
                $map[] = ['user_id', 'eq', $data['keyword']];
            }
            if (isset($data['group_id']) && !empty($data['group_id'])) {
                $map[] = ['group_id', 'eq', $data['group_id']];
            }
            if (isset($data['status']) && $data['status'] != '') {
                $map[] = ['status', 'eq', $data['status']];
            } else {
                $map[] = ['status', 'neq', 5];
            }
            $page   = isset($data['page']) ? $data['page'] : 1;
            $limit  = isset($data['limit']) ? $data['limit'] : 15;

            $_map = [];
            $_map[] = ['exp_time', 'gt', 0];
            $_map[] = ['exp_time', 'lt', time()];
            $this->UserGroupCodekeyModel->where($_map)->update(['status' => 5]);

            $data = $this->UserGroupCodekeyModel->getList($map, $page, $limit);

            return $this->success('获取成功', '', $data);
        }
        return $this->fetch();
    }

    public function createCodekey()
    {
        if ($this->request->isAjax()) {
            $data   = input();
            if ($data['number'] > 1000) {
                return $this->error("为降低服务器压力，每次生成的数量不可超过1000个");
            }
            $exp_time = $data['exp_time'];
            if ($exp_time > 0) {
                $exp_time = abs($exp_time);
                $exp_time = time() + ($exp_time * 60);
            }
            
            $i = 1;
            $sql = 'INSERT INTO ' . config('database.prefix') 
            . 'user_group_codekey(`id`, `user_id`, `group_id`, `codekey`, `status`, `exp_time`, `code_type`, `use_num`, `create_time`, `update_time`) VALUES';
            $time = time();
            while ($i <= $data['number']) {
                $uniqid = substr(md5(random(16, 0) . $time), 3, 12);
                $sql .= '(0, 0, ' . $data['group_id'] . ',"' . $uniqid . '", 0, ' . $exp_time . ', ' . $data['code_type'] . ', ' . $data['use_num'] . ', ' . $time . ', ' . $time . ')'
                    . (($i == $data['number']) ? ';' : ',');
                $i++;
            }
            $this->UserGroupCodekeyModel->query($sql);
            return $this->success('生成成功');
        }
        $group = UserGroup::getGroupList();
        $this->assign('group', $group);
        return $this->fetch('form');
    }

    public function export()
    {
        $map = [];
        $map[] = ['status', 'eq', 0];
        $data = $this->UserGroupCodekeyModel->getList($map);
        $header = array('卡密');
        $index = array('codekey');

        $this->exportExcel($data['list'], 'codekey', $header, $index);
    }

    /**
     * 创建(导出)Excel数据表格
     * @param  array   $list 要导出的数组格式的数据
     * @param  string  $filename 导出的Excel表格数据表的文件名
     * @param  array   $header Excel表格的表头
     * @param  array   $index $list数组中与Excel表格表头$header中每个项目对应的字段的名字(key值)
     * 比如: $header = array('编号','姓名','性别','年龄');
     *       $index = array('id','username','sex','age');
     *       $list = array(array('id'=>1,'username'=>'YQJ','sex'=>'男','age'=>24));
     * @return [array] [数组]
     */
    protected function exportExcel($list, $filename, $header = array(), $index = array())
    {
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:filename=" . $filename . ".xls");
        $teble_header = implode("\t", $header);
        $strexport = $teble_header . "\r";
        foreach ($list as $row) {
            foreach ($index as $val) {
                $strexport .= '' . $row[$val] . "\t";
            }
            $strexport .= "\r";
        }
        $strexport = iconv('UTF-8', "GB2312//IGNORE", $strexport);
        exit($strexport);
    }
    /**
     * 卡密使用情况
     *
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function countNum()
    {
        $data = cache('codekey_count');
        if (!$data) {
            $map = [];
            $data['count'] = $this->UserGroupCodekeyModel->where($map)->count('id');
            $map = [];
            $map[] = ['status', 'eq', 0];
            $data['unuse'] = $this->UserGroupCodekeyModel->where($map)->count('id');
            $map = [];
            $map[] = ['status', 'eq', 1];
            $data['used'] = $this->UserGroupCodekeyModel->where($map)->count('id');
            $data['group'] = [
                'used' => '',
                'nused' => '',
            ];
            $group = UserGroup::getGroupList();
            foreach ($group as $k => $v) {
                $map = [];
                $map[] = ['status', 'eq', 1];
                $map[] = ['group_id', 'eq', $v['value']];
                $data['group']['used'] .= $v['label'] . '：' . $this->UserGroupCodekeyModel->where($map)->count('id') . '个；';
                $map = [];
                $map[] = ['status', 'eq', 0];
                $map[] = ['group_id', 'eq', $v['value']];
                $data['group']['nused'] .= $v['label'] . '：' . $this->UserGroupCodekeyModel->where($map)->count('id') . '个；';
            }
            cache('codekey_count', $data, 300);
        }
        return $this->success('成功', '', $data);
    }

    public function deleteAll($status = '')
    {
        if ($status == '') {
            return $this->error('请选择要删除的兑换码状态');
        }
        $map = [];
        $map[] = ['status', 'eq', $status];
        $this->UserGroupCodekeyModel->where($map)->delete();
        return $this->success('删除成功');
    }
}
